package com.masu.knows.portal.controller;

import com.masu.knows.portal.dto.RegisterDTO;
import com.masu.knows.portal.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.UUID;

/**
 * @author 沈传尚
 * @date 2021/12/23
 */
@RestController
@Slf4j
@RequestMapping(value = "/register")
public class SystemController {
    @Autowired
    private UserServiceImpl userService;

    @Value("${knows.resource.path}")
    private File resourcePath;

    @Value("${knows.resource.host}")
    private String resourceHost;


    @RequestMapping(value = "/student",method = RequestMethod.POST)
    //@Validated表示激活后面类型的Spring Validation验证
    //在需要验证的方法参数后添加指定类型(BindingResult)的参数 验证结果会自动赋值到这个参数中
    public String registerStudent(@Validated RegisterDTO registerDTO , BindingResult result){
        try {
            log.debug("收到注册信息:{}",registerDTO);
            // 判断验证有没有错误
            if (result.hasErrors()){
                return  Objects.requireNonNull(result.getFieldError()).getDefaultMessage();
            }
            userService.registerStudent(registerDTO);
            return "ok";
        } catch (Exception e) {
            return e.getMessage();
        }

    }


    @PostMapping(value = "/upload/image")
    public String uploadImage(MultipartFile imageFile) throws IOException {
        String path = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        File folder=new File(resourcePath,path);
        folder.mkdirs();
        log.debug("上传的文件夹为:{}", folder.getAbsolutePath());
        String filename = imageFile.getOriginalFilename();
        String ext = null;
        if (!Objects.isNull(filename)) {
            ext = filename.substring(filename.lastIndexOf("."));
        }else {
            return "文件名有误!";
        }
        // 生成UUID确定文件名称
        String name=UUID.randomUUID().toString().replaceAll("-","")+ext;
        File file=new File(folder,name);
        log.debug("最终的上传的路径:{}",file.getAbsolutePath());
        imageFile.transferTo(file);
        // http://localhost:8899/2022/04/02/b50d04efaea34182b9757ea117d20c70.png
        return resourceHost+"/"+path+"/"+name;
    }


}
